package com.simple.sso.client.filter;

import com.simple.sso.client.utils.HttpUtils;
import com.simple.sso.client.utils.SessionStorage;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Component
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    //注意：这里的filterConfig对象中封装了initParameters的值
    private FilterConfig config;

    //init方法参数为filterConfig对象，可以获取ilterBean.setInitParameters(Map)中的初始化参数值
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        config = filterConfig;
        System.out.println("sso-client init method...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("sso-client doFilter method...");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        //局部session存在，则表示为已登录（局部会话有效，则全局会话肯定有效）
        if (session.getAttribute("isLogin") != null) {
            filterChain.doFilter(request, response);
            return;
        }

        //通过sso-server，认证中心认证过了，获取到有效的令牌，这里也表示登录成功；（全局会话有效，则登录成功）
        //todo 如何判断这个token令牌有效？
        String token = request.getParameter("token");
        boolean isTokenValid = true;
        if (!StringUtils.isEmpty(token)) {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("token", token);
            isTokenValid = HttpUtils.checkGlobleSessionValid(config.getInitParameter("checkTokenValidUrl"), paramMap);
        }

        if (token != null && isTokenValid) {
            session.setAttribute("token", token);
            session.setAttribute("isLogin", true);
            //容器中存储token和session值，单点注销时使用
            SessionStorage.INSTANCE.set(token, session);
            filterChain.doFilter(request, response);
            return;
        }

        //局部会话和全局会话都没有，表示当前未登录，则需要跳转到认证中心，进行登录验证；
        //http://localhost:8080/server?clientUrl=http://localhost:8083/sysb/success
        String redirectLoginUrl = config.getInitParameter("loginUrl") + "?clientUrl=" + request.getRequestURL();
        response.sendRedirect(redirectLoginUrl);
    }

    @Override
    public void destroy() {
        System.out.println("sso-client destroy method...");
    }
}
